/**
 * File:		Server.java
 * Project:		Virtual Advisor
 * Module:		Data Management
 * Author:		Rotem Ganel
 * Created:		Apr 24, 2011
 * Updated:		Apr 24, 2011
 * Version:		1 (in progress)
 * 
 * Adapted from Oracle Java Socket Tutorial
 * http://www.oracle.com/technetwork/java/socket-140484.html#server
 */
package server.serverApp;

import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.IOException;
import java.net.ServerSocket;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

import server.dataManagement.RequestInterpreter;

class Server {
	private static final String CATALOG = "Catalog.xml";
	private static final String CURRICULUM = "Curriculum.xml";
	private static final String USERS = "Users.xml";
	private ServerSocket server = null;

	public Server() throws IOException {
		this(2222);
	}
	
	public Server(int port) throws IOException {
		server = new ServerSocket(port);
		
		  JPanel panel	= new JPanel(new GridLayout(3,1));
		  panel.setPreferredSize(new Dimension(150, 150));
		  
		  final JFrame frame = new JFrame();
		  JLabel label = new JLabel("Server is running.");
		  JButton button = new JButton("Terminate");
		  
		  panel.add(label);
		  panel.add(button);
		  
		  button.addActionListener(new ActionListener() {
			 public void actionPerformed(ActionEvent e) {
					JOptionPane.showMessageDialog(frame, "Connection closed.");
					System.exit(0);
			 }
		  });
		  
		  frame.add(panel);
		  frame.pack();
		  frame.setVisible(true);
		  
		  frame.addWindowListener (new WindowAdapter() {
				public void windowClosing(WindowEvent e) {
					JOptionPane.showMessageDialog(frame, "Connection closed.");
					System.exit(0);
				}
			});
		
//		System.out.println(server.getInetAddress());
//		InetAddress thisIp = InetAddress.getLocalHost();
//	     System.out.println("Local host: " + thisIp);
//	     System.out.println("Host address: " + thisIp.getHostAddress());
	}

	public void connect() throws IOException {
		while (true) {
			ServerPortal portal;
	        portal = new ServerPortal(server.accept());
	        Thread t = new Thread(portal);
	        t.start();
		}
	}

	protected void finalize() throws IOException {
	//Objects created in run method are finalized when 
	//program terminates and thread exits
		server.close();
	}

	public static void main(String[] args){
		try {
			RequestInterpreter.setFilenames(CATALOG, CURRICULUM, USERS);
			Server server = new Server();
			server.connect();
		} catch (IOException e) {
			e.printStackTrace();
		}	
	}
}
